const Answer = require('../models/answers')
const User = require('../models/users')
class AnswersCtl {
  // 检查答案是否存在中间件
  async checkAnswerExist(ctx, next) {
    const answer = await Answer.findById(ctx.params.id).select('+answerer')
    if (!answer) {
      ctx.throw(404, '该答案不存在')
    }
    // 只有删改查答案才检查此逻辑，赞、踩答案时不检查
    if (ctx.params.questionId && answer.questionId !== ctx.params.questionId) {
      ctx.throw(404, '该问题下没有此答案')
    }
    ctx.state.answer = answer
    await next()
  }
  // 检查是否是答案回答者中间件
  async checkAnswerer(ctx, next) {
    const { answer } = ctx.state
    if (answer.answerer._id.toString() !== ctx.state.user._id) {
      ctx.throw(403, '没有权限')
    }
    await next()
  }
  // 获取答案列表
  async find(ctx) {
    const { per_page = 10 } = ctx.query
    // 当前页
    const page = Math.max(ctx.query.page * 1, 1) - 1
    // 每页显示多少条，同时防止小于1的情况
    const perPage = Math.max(per_page * 1, 1)
    const q = new RegExp(ctx.query.q)
    // 匹配content的模糊查询
    ctx.body = await Answer.find({
      content: q,
      questionId: ctx.params.questionId
    })
      .limit(perPage)
      .skip(page * perPage)
  }
  // 获取指定答案
  async findById(ctx) {
    const { fields = '' } = ctx.query
    const selectedFields = fields
      .split(';')
      .filter(v => v)
      .map(v => ' +' + v)
      .join('')
    const answer = await Answer.findById(ctx.params.id)
      .select(selectedFields)
      .populate('answerer')
    ctx.body = answer
  }
  // 新建答案
  async create(ctx) {
    ctx.verifyParams({
      content: { type: 'string', required: true }
    })
    const answer = await new Answer({
      ...ctx.request.body,
      answerer: ctx.state.user._id,
      questionId: ctx.params.questionId
    }).save()
    ctx.body = answer
  }
  // 修改指定答案
  async update(ctx) {
    ctx.verifyParams({
      content: { type: 'string', required: false }
    })
    await ctx.state.answer.update(ctx.request.body)
    ctx.body = ctx.state.answer
  }
  // 删除指定答案
  async delete(ctx) {
    await answer.findByIdAndRemove(ctx.params.id)
    ctx.status = 204
  }
}
module.exports = new AnswersCtl()
